/*  This file is part of Cobra.

    Cobra is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Cobra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Cobra.  If not, see <http://www.gnu.org/licenses/>.

    http://code.google.com/p/cobra-extension/
    Igor Demyanov Igor.demyanov@gmail.com
    Dmitry Gribanov tux.spb@gmail.com
*/

var CobraChromeExt={
/* default options */
_involvedDisable:false,
_involvedWindowOffY:5,
_involvedWindowOffX:0,
_involvedPreferencesControl:null,
/* Global hook Start */
activateGlobalHook:function(){
	document.body.addEventListener('keyup',this._bodyKeyUp,false);
},
deactivateGlobalHook:function(){
	document.body.removeEventListener('keyup',this._bodyKeyUp,false);
},

_bodyKeyUp:function(e){
	if (e.keyCode==13){
		var options = CobraChromeExt._involvedPreferencesControl;
		var password_length = CobraChromeExt.getOptionValue(CobraChromeExt._involvedPreferencesControl,'input[type="radio"]:checked'); 
		var no_specials = CobraChromeExt.getOptionValue(CobraChromeExt._involvedPreferencesControl,'input[type="checkbox"]:checked')== undefined ? false : true;
					
		if (password_length == undefined){password_length = 8;}
		chrome.extension.sendRequest( {
					action : 'CalcPassword',
					master : CobraChromeExt._involvedMasterKey.value,
					tag : CobraChromeExt._involvedTag.value,
					hashWordSize : password_length,
					restrictSpecial : no_specials
						}, function(response) {
							CobraChromeExt._password.value = response.content;
						});
		CobraChromeExt._involvedMasterKeyKeyUp({keyCode:27});//ESC
	}
},
/* Global hook End */

/* Involved Start */


_involvedPreferencesShowHide:function(e){
			var options = CobraChromeExt._involvedPreferencesControl;
			if (options != null) {
				CobraChromeExt.removeClass(CobraChromeExt._involvedPreferences,'cobra-involved-preferences-expand');
				CobraChromeExt._involvedWindow.removeChild(options);
				CobraChromeExt._involvedPreferencesControl=null;
			} else {
				chrome.extension.sendRequest({action : 'GetTemplate',template:'options'},
						function(response) {
							CobraChromeExt.addClass(CobraChromeExt._involvedPreferences,'cobra-involved-preferences-expand');
							var options = document.createElement('div');
							options.id='cobra-involved-options';
							options.innerHTML=response.content;
							CobraChromeExt._involvedPreferencesControl = options;
							CobraChromeExt._involvedWindow.appendChild(options);
							});
			}
},
_involvedMasterKeyKeyUp:function (e) {
					switch (e.keyCode) {
					/*case 13:*/
						
					case 27:
						CobraChromeExt._involvedDisable = true;
						CobraChromeExt.deactivateGlobalHook();
						CobraChromeExt._involvedMasterKey.value = '';
						CobraChromeExt.effectHide(CobraChromeExt._involvedWindow);
						CobraChromeExt._password.focus();
						break;
					}
				},
//Window
createInvolvedWindow:function(siteTag){
 	var div = document.createElement('div');
 div.id='cobra-involved-window';
 div.innerHTML='<input id="cobra-involved-tag" value="' + siteTag + '" /><br />' + '<input id="cobra-involved-master-key" type="password"/><div id="cobra-involved-preferences" title="Preferences"></div>'+
'<a href="http://code.google.com/p/cobra-extension/issues/list" class="cobra-feedback">feedback</a>';
	document.body.appendChild(div);	
	this._involvedTag = document.getElementById('cobra-involved-tag');
	this._involvedMasterKey=document.getElementById('cobra-involved-master-key');
	this._involvedMasterKey.addEventListener('keyup',this._involvedMasterKeyKeyUp,false);

	this._involvedPreferences = document.getElementById('cobra-involved-preferences');
	this._involvedPreferences.addEventListener('click',this._involvedPreferencesShowHide,false);

	this._involvedWindow = div;

},

/* Involved End */

setCurrentPasswordElement:function(passElement){
	this._password = passElement;
	if (passElement.value == '' && this._involvedDisable == false) {
		var xy = this.getAbsolutePos(passElement);
		var win = this._involvedWindow;
		win.style.top = xy.y + this._involvedWindowOffY + passElement.offsetHeight + 'px';
		win.style.left = xy.x + this._involvedWindowOffX + 'px';
		this.effectShow(win);
		
		this.activateGlobalHook();
		this._involvedMasterKey.value='';
		this._involvedMasterKey.focus();
	}else{
		this._involvedDisable = false;
	}
},


/* Utils */
getDomain:function(input) {
		var h = input.split(".");
		return (h[h.length - 2]);
},
getOptionValue:function (optionsElement,query){
	if (optionsElement == null || optionsElement == undefined){
		return undefined;
	}
	var element = optionsElement.querySelector(query);
 if (element == null){
 	return undefined;
 }else
{
	return element.value;
}
},
/* jQuery min */
jsM:function (oArr,func,args){
	for(var i = 0 ; i< oArr.length;i++){
		//arguments
		func.apply(oArr[i],args);
	}
},
//returns absolute position of some element within document  
getAbsolutePos:function(element) {  
    var res = new Object();  
    res.x = 0; res.y = 0;  
    if (element !== null) {  
        res.x = element.offsetLeft;  
        res.y = element.offsetTop;  
          
        var offsetParent = element.offsetParent;  
        var parentNode = element.parentNode;  
        var borderWidth = null;  
  
        while (offsetParent != null) {  
            res.x += offsetParent.offsetLeft;  
            res.y += offsetParent.offsetTop;  
              
            var parentTagName = offsetParent.tagName.toLowerCase();   
         
            if (offsetParent != document.body && offsetParent != document.documentElement) {  
                res.x -= offsetParent.scrollLeft;  
                res.y -= offsetParent.scrollTop;  
            }  
  
            //next lines are necessary to support FireFox problem with offsetParent  
                while (offsetParent != parentNode && parentNode !== null) {  
                    res.x -= parentNode.scrollLeft;  
                    res.y -= parentNode.scrollTop;  
                 
                    parentNode = parentNode.parentNode;  
                }      
            
            parentNode = offsetParent.parentNode;  
            offsetParent = offsetParent.offsetParent;  
        }  
    }  
    return res;  
},  
trim:function( text ) {//jQuery 1.4.2
	// Used for trimming whitespace
		return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );
},
removeClass:function(elem,value){//jQuery 1.4.2
	var classNames = (value || "").split(/\s+/);
				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						var className = (" " + elem.className + " ").replace(/[\n\t]/g, " ");
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[c] + " ", " ");
						}
						elem.className = this.trim( className );

					} else {
						elem.className = "";
					}
				}
},
addClass:function(elem,value){//jQuery 1.4.2
	var classNames = (value || "").split( /\s+/ );
				if ( elem.nodeType === 1 ) {
					if ( !elem.className ) {
						elem.className = value;

					} else {
						var className = " " + elem.className + " ", setClass = elem.className;
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
								setClass += " " + classNames[c];
							}
						}
						elem.className = this.trim( setClass );
					}
				}
},
effectShow:function(element){
	//element.style.display="block";
	element.style.opacity=1;
	element.style.zIndex=10000;
	
},
effectHide:function(element){
	element.style.opacity=0;
	//element.style.display="none";
	element.style.zIndex=-10000;
}
};
